using Lzfy_His_Service.Models;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Lzfy_His_Service.Services
{
    /// <summary>
    /// 患者退费信息查询服务实现
    /// </summary>
    public class PatientRefundQueryService : IPatientRefundQueryService
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<PatientRefundQueryService> _logger;

        public PatientRefundQueryService(IConfiguration configuration, ILogger<PatientRefundQueryService> logger)
        {
            _configuration = configuration;
            _logger = logger;
        }

        /// <summary>
        /// 通过患者ID查询退费信息
        /// </summary>
        /// <param name="patientId">患者ID</param>
        /// <returns>患者退费信息列表</returns>
        public async Task<List<PatientRefundInfo>> GetPatientRefundInfoAsync(string patientId)
        {
            var result = new List<PatientRefundInfo>();

            try
            {
                var connectionString = _configuration.GetConnectionString("DefaultConnection");
                
                using var connection = new SqlConnection(connectionString);
                await connection.OpenAsync();

                var query = @"
                    SELECT 
                        input_date,
                        refund_amount,
                        refund_balance,
                        audit_result,
                        audit_comment
                    FROM lzfy_refund_master
                    WHERE patient_id = @patientId
                    ORDER BY input_date DESC";

                using var command = new SqlCommand(query, connection);
                command.Parameters.AddWithValue("@patientId", patientId);

                using var reader = await command.ExecuteReaderAsync();
                
                while (await reader.ReadAsync())
                {
                    var auditResult = reader["audit_result"]?.ToString();
                    var auditResultDescription = GetAuditResultDescription(auditResult);
                    var auditComment = reader["audit_comment"]?.ToString();
                    
                    // 判断refund_amount是否为空，如果为空则返回refund_balance，否则返回refund_amount
                    var refundAmount = reader["refund_amount"] as decimal?;
                    var refundBalance = reader["refund_balance"] as decimal?;
                    var finalRefundValue = refundAmount ?? refundBalance;

                    result.Add(new PatientRefundInfo
                    {
                        InputDate = reader["input_date"] as DateTime?,
                        RefundBalance = finalRefundValue,
                        AuditResult = auditResult,
                        AuditResultDescription = auditResultDescription,
                        AuditComment = auditComment
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询患者退费信息失败，患者ID: {PatientId}", patientId);
                throw;
            }

            return result;
        }

        /// <summary>
        /// 获取审核结果描述
        /// </summary>
        /// <param name="auditResult">审核结果代码</param>
        /// <returns>审核结果描述</returns>
        private string GetAuditResultDescription(string? auditResult)
        {
            return auditResult switch
            {
                "0" => "已申请线上退费",
                "1" => "已通过退费审核",
                "2" => "退费审核已被拒绝",
                _ => "未知状态"
            };
        }
    }
}